import os
from flask import Flask
import subprocess as sub
import config


def execute(command):
    p = sub.Popen(command, stdout=sub.PIPE, stderr=sub.PIPE, shell=True)
    output, errors = p.communicate()
    return output, errors


def execute_return_html(command):
    print command
    output, errors = execute(command)
    html = output.replace('\n', '<br>')
    if len(errors) > 0:
        html += '<br>'
        html += errors.replace('\n', '<br>')
    return html


app = Flask(__name__)
base_path = os.path.split(os.path.realpath(__file__))[0]
python_bin = 'python'

conf = config.load_config()
if conf is None:
    print 'please check config.json'
    exit(1)

url = conf.web_config.url
port = conf.web_config.port


@app.route('/%s/1' % url)
def create_alloc_start_install():
    return execute_return_html('%s %s 1' % (python_bin, os.path.join(base_path, 'main.py')))


@app.route('/%s/2' % url)
def stop_delete_all():
    return execute_return_html('%s %s 2' % (python_bin, os.path.join(base_path, 'main.py')))


@app.route('/%s/3' % url)
def show_all():
    return execute_return_html('%s %s 3' % (python_bin, os.path.join(base_path, 'main.py')))


@app.route('/%s/4' % url)
def load_config():
    return execute_return_html('%s %s 4' % (python_bin, os.path.join(base_path, 'main.py')))


@app.route('/%s/0' % url)
def empty():
    return "empty"


if __name__ == '__main__':
    print 'url', url
    app.run(host='0.0.0.0', port=port, threaded=True)
